<template>
	<view v-if="isView" style="background: #ffffff;">
		<custom-nav v-if="systemtype == 'h5'" v-bind="navConfig"></custom-nav>
		<div class="wrapper">
			<div class="container">
				<div class="mod-panel">
					<div class="inner">
						<div class="bd Media--alignCenter">
							<div id="screenshotTarget" class="view-box">
								<component v-if="visible" :is="activeConfig.com" :info="programmeData"
									:backgroundImage="backgroundImage">
									<img v-if="qrcodePic" :style="{width: qrcodeStyle.width, height: qrcodeStyle.height}"
										:src="qrcodePic">
									<widget-qrcode ref="codeID" :value="qrcodeData.value"
										:template="qrcodeData.template" :width="qrcodeData.width"
										:height="qrcodeData.height" :background-color="qrcodeData['background-color']"
										:foreground-color="qrcodeData['foreground-color']"
										:inner-color="qrcodeData['inner-color']"
										:outer-color="qrcodeData['outer-color']" :level="qrcodeData.level"
										:background-image="qrcodeData['background-image']"
										:foreground-image="qrcodeData['foreground-image']" :logo="qrcodeData.logo"
										:text="qrcodeData.text" :text-color="qrcodeData['text-color']"
										:text-stroke="qrcodeData['text-stroke']"></widget-qrcode>
								</component>
								<div class="Grid Grid--center Grid--justifyCenter text-center"
									style="position: absolute; width: 375px; left: 0; bottom: -40px; padding: 10px 0; background: rgba(0, 0, 0, .4);"
									@click="captureScreenshot">
									<view>
										<u--text prefixIcon="download" iconStyle="font-size: 19px" text="下载"
											color="#ffffff" :iconStyle="{color: '#ffffff'}"></u--text>
									</view>
								</div>
							</div>
							<div class="setting-box">
								<div v-if="type==3||type==4" class="Media Media--center" style="padding: 5px;">
									<div style="width: 80px; font-size: 14px; color: #666666;">选择类型</div>
									<div class="Media-body">
										<view class="Grid Grid--center text-sm custom-select-btn">
											<view :class="['item', {active: userType == 1}]" @click="setUserType(1)">新用户</view>
											<view :class="['item', {active: userType == 2}]" @click="setUserType(2)">老用户</view>
										</view>
									</div>
								</div>
								<div v-if="type==3||type==4" class="Media Media--center" style="padding: 5px;">
									<div style="width: 80px; font-size: 14px;  color: #666666; text-align: center;">海报模板</div>
									<div class="Media-body">
										<div class="Grid Grid--center Grid--justifySpaceBetween">
											<div v-if="type==3" v-for="(item,index) in 10" :key="'zq'+index"
												style="display: inline-block;margin-bottom: 10px;cursor: pointer;">
												<img @click="getTemplate(item)" width="90px"
													:style="selectTemplate==item?'border: 2px solid #fd7640; box-sizing: border-box;':''"
													:src="require(`../../static/images/poster/soccer-${item}.png`)"
													alt="">
											</div>
											<div v-if="type==4" v-for="(item,index) in 10" :key="'lq'+index"
												style="display: inline-block;margin-bottom: 10px;cursor: pointer;">
												<img @click="getTemplate(item)" width="90px"
													:style="selectTemplate==item?'border: 2px solid #fd7640; box-sizing: border-box;':''"
													:src="require(`../../static/images/poster/basketball-${item}.png`)"
													alt="">
											</div>
										</div>
									</div>
								</div>
								<div class="Media Media--center" style="padding: 5px;">
									<div style="width: 80px; font-size: 14px;  color: #666666; text-align: center;">海报背景</div>
									<div class="Media-body">
										<div v-if="backgroundImage">
											<div class="poster-box-item active" style="width: 80px;">
												<u--image :showLoading="true" mode="aspectFill" :src="backgroundImage"
													width="80px" height="116px"></u--image>
												<div style="position: absolute; width: 30px; right: -10px; top: -10px;">
													<div class="Grid Grid--center Grid--justifyFlexEnd">
														<u-icon color="rgb(192, 196, 204)" size="18"
															name="close-circle-fill" style="padding: 5px;" @click="() => {
															backgroundImage = ''
														}"></u-icon>
													</div>
												</div>
											</div>
										</div>
										<u-button style="width: 140px; margin-left: 0; height: 34px;" type="primary"
											text="上传自定义背景" @click="openPoster"></u-button>
										<div style="width: 100%; font-size: 12px; color: #999999;">尺寸: 竖版750*1105 / 横版750*417</div>
									</div>
								</div>
								<div class="Media Media--center" style="padding: 5px;">
									<div style="width: 80px; font-size: 14px;  color: #666666; text-align: center;">风格模板<div style="font-size: 12px; color: #999999;">二维码</div></div>
									<div class="Media-body">
										<radio-group @change="e => {
											handleTemplate({template: e.detail.value})
										}">
											<label v-for="(item, index) in templateList" :key="index"
												style="margin-bottom: 5px; font-size: 14px;">
												<radio :value="item.name" activeBackgroundColor="#52B36D"
													:checked="qrcodeData.template == item.name"
													style="transform:scale(0.7)" />{{item.label}}
											</label>
										</radio-group>
									</div>
								</div>
								<div class="Media Media--center" style="padding: 5px;">
									<div style="width: 80px; font-size: 14px;  color: #666666; text-align: center;">颜色方案<div style="font-size: 12px; color: #999999;">二维码</div></div>
									<div class="Media-body Media--center">
										<div class="Grid Grid--center text-xs">
											<u-tag size="mini" borderColor="rgb(220, 223, 230)"
												:bgColor="qrcodeData['foreground-color'] || 'transparent'"
												style="display: inline-block; width: 34px; cursor: pointer;"
												@click="handlepickColor('foreground-color')"></u-tag>
											<div style="padding: 0 5px;">前景色</div>
											<u-tag size="mini" borderColor="rgb(220, 223, 230)"
												:bgColor="qrcodeData['background-color'] || 'transparent'"
												style="display: inline-block; width: 34px; cursor: pointer;"
												@click="handlepickColor('background-color')"></u-tag>
											<div style="padding: 0 5px;">背景色</div>
											<u-tag size="mini" borderColor="rgb(220, 223, 230)"
												:bgColor="qrcodeData['inner-color'] || 'transparent'"
												style="display: inline-block; width: 34px; cursor: pointer;"
												@click="handlepickColor('inner-color')"></u-tag>
											<div style="padding: 0 5px;">定位内框</div>
											<u-tag size="mini" borderColor="rgb(220, 223, 230)"
												:bgColor="qrcodeData['outer-color'] || 'transparent'"
												style="display: inline-block; width: 34px; cursor: pointer;"
												@click="handlepickColor('outer-color')"></u-tag>
											<div style="padding: 0 5px;">定位外框</div>
										</div>
									</div>
								</div>
								<div class="Media Media--center" style="padding: 5px;">
									<div style="width: 80px; font-size: 14px;  color: #666666; text-align: center;">系统预设<div style="font-size: 12px; color: #999999;">二维码</div></div>
									<div class="Media-body Media--center">
										<widget-qrcode v-for="(item, index) in systemPreset"
											:key="`system_preset_${index}`" :value="item.value"
											:template="item.template" :width="item.width" :height="item.height"
											:background-color="item['background-color']"
											:foreground-color="item['foreground-color']"
											:inner-color="item['inner-color']" :outer-color="item['outer-color']"
											:level="item.level" :background-image="item['background-image']"
											:foreground-image="item['foreground-image']" :logo="item.logo"
											:text="item.text" :text-color="item['text-color']"
											:text-stroke="item['text-stroke']"
											style="margin: 0 5px 5px 0; cursor: pointer;"
											@click="handleSystemPreset(item)"></widget-qrcode>
									</div>
								</div>

								<div class="Media Media--center" style="padding: 5px;">
									<div style="width: 80px; font-size: 14px;  color: #666666; text-align: center;">设置logo</div>
									<div class="">
										<u-button style="width: 100px; height: 34px;" type="primary" text="上传logo"
											@click="posterAfterRead(3)"></u-button>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
		<uv-pick-color v-if="isUvPickColor" ref="pickColor" :scrollTop="pickColorData.scrollTop"
			:title="pickColorData.title" :color="pickColorData.color" @confirm="confirm" @cancel="cancel"
			@close="close"></uv-pick-color>
		<!-- 选择海报背景 -->
		<uni-popup ref="posterPopup" type="bottom" background-color="#fff" borderRadius="10px 10px 0 0"
			mask-background-color="rgba(0,0,0,0.6)">
			<view class="popup">
				<view class="close-popup">
					<text>选择海报背景</text>
					<u-icon @click="() => {$refs.posterPopup.close()}" size="14" bold name="close" style="position: absolute; right: 0; padding: 5px;"></u-icon>
				</view>
				<view>
					<scroll-view scroll-y="true" style="height: 50vh;">
						<view v-if="fileList.length" class="Grid Grid--1of3">
							<view class="Grid-cell" v-for="(item, index) in fileList" :key="index"
								style="margin-bottom: 10px;">
								<view class="Grid Grid--center Grid--justifyCenter relative">
									<u--image :showLoading="true" :src="item.file_url" width="80px" height="80px"
										mode="aspectFit" @click="selectCustomPoster(item.file_url)"></u--image>
									<view style="position: absolute; top: 0; right: 0; padding: 5px;"
										@click="deletePic(item)">
										<u-icon color="rgb(192, 196, 204)" name="close-circle-fill"></u-icon>
									</view>
								</view>
							</view>
						</view>
						<u-empty v-if="!fileList.length" mode="list" :icon="emptyList" text="暂无自定义海报背景">
						</u-empty>
					</scroll-view>
					<view class="Grid Grid--center Grid--justifyCenter" style="width: 100%; padding: 10px 0 5px;">
						<u-button style="width: 80vw;" type="primary" text="上传海报背景"
							@click="posterAfterRead(1)"></u-button>
						<view class="text-sm" style="width: 80vw; color: #f56c6c;">尺寸: 竖版750*1105 / 横版750*417</view>
					</view>

				</view>
			</view>
		</uni-popup>
		<view v-if="downloadImage" class="Grid Grid--center Grid--justifyCenter"
			style="position: fixed; top: 0; left: 0; bottom: 0; width: 100%; background: rgba(0, 0, 0, .8);"
			@click="downloadImage = ''">
			<div style="width: 320px;display: inline-grid;">
				<image :src="downloadImage" mode="widthFix"></image>
				<div class="Grid Grid--center Grid--justifyCenter text-center"
					style="background: rgba(111, 110, 110, 0.6);color: #fff;padding: 6px;font-size: 14px;">
					长按图片保存
				</div>
			</div>
			<!-- <div class="text-white text-sm">长按保存</div> -->
		</view>
	</view>
</template>

<script>
	import navConfig from './config/navConfig.js'
	import html2canvas from 'html2canvas'
	import {
		mapState
	} from "vuex";
	import {
		getDetailsinfo,
		getCode,
		fileList,
		deleFile
	} from '@/service/index'
	import emptyList from '@/static/images/my/list.png'

	// 足球
	import tempFootball1 from './template/temp-football-1.vue'
	import tempFootball2 from './template/temp-football-2.vue'
	import tempFootball3 from './template/temp-football-3.vue'
	import tempFootball4 from './template/temp-football-4.vue'
	import tempFootball5 from './template/temp-football-5.vue'
	import tempFootball6 from './template/temp-football-6.vue'
	import tempFootball7 from './template/temp-football-7.vue'
	import tempFootball8 from './template/temp-football-8.vue'
	import tempFootball9 from './template/temp-football-9.vue'
	import tempFootball10 from './template/temp-football-10.vue'
	// 籃球
	import tempBasketball1 from './template/temp-basketball-1.vue'
	import tempBasketball2 from './template/temp-basketball-2.vue'
	import tempBasketball3 from './template/temp-basketball-3.vue'
	import tempBasketball4 from './template/temp-basketball-4.vue'
	import tempBasketball5 from './template/temp-basketball-5.vue'
	import tempBasketball6 from './template/temp-basketball-6.vue'
	import tempBasketball7 from './template/temp-basketball-7.vue'
	import tempBasketball8 from './template/temp-basketball-8.vue'
	import tempBasketball9 from './template/temp-basketball-9.vue'
	import tempBasketball10 from './template/temp-basketball-10.vue'
	// 籃球

	import pic_1 from './image/bg/girl.jpeg'
	import pic_2 from './image/bg/monkey.jpeg'
	import pic_3 from './image/logo/snail.png'
	import pic_3_1 from './image/skin/grass.png'
	import pic_4 from './image/logo/earth.png'
	import pic_5 from './image/logo/octopus.png'
	import {
		addFile
	} from '@/service/index.js'

	// 图片转base64
	export const imageToBase64 = (path) => {
		// #ifdef APP-PLUS
		return new Promise((resolve, reject) => {
			plus.io.resolveLocalFileSystemURL(path, function(entry) {
				entry.file(function(file) {
					var fileReader = new plus.io.FileReader();
					fileReader.readAsDataURL(file);
					fileReader.onloadend = function(evt) {
						resolve(evt.target.result);
					}
				})
			})
		})
		// #endif

		// #ifdef H5
		return new Promise((resolve, reject) => {
			uni.request({
				url: path,
				method: 'GET',
				responseType: 'arraybuffer',
				success: res => {
					let base64 = uni.arrayBufferToBase64(res.data); //把arraybuffer转成base64
					base64 = 'data:image/jpeg;base64,' + base64
					resolve(base64)
				},
				fail: err => {
					reject(err)
				}
			})
		})
		// #endif
	}

	export default {
		data() {
			return {
				navConfig,
				emptyList,
				isView: false,
				selectTemplate: 1,
				type: 4, // 3 足球 4 篮球
				visible: true,
				isUvPickColor: false,
				activeConfig: {
					com: ''
				},
				pic_1,
				pic_2,
				pic_3,
				pic_3_1,
				pic_4,
				pic_5,
				qrcodeData: {
					value: '', // 二维码内容
					template: 'default', // 样式模板,可选：'default','water','diamond','hexagon','star','rect','bar','heart','glitter','stroke','fusion',
					level: '', // 纠错等级,可选：'M','L','Q','H'
					width: 112, // 二维码宽度，默认：300,
					height: 112, // 二维码高度，默认：300
					'background-color': '#ffffff', // 背景色，默认：#ffffff
					'foreground-color': '#000000', // 前景色，默认：#000000;（多色用逗号分隔）
					'inner-color': '#000000', // 定位点内层颜色，默认：#000000
					'outer-color': '#000000', // 定位点外层颜色，默认：#000000
					'background-image': '', // 背景图片地址
					'foreground-image': '', // 前景图片地址
					logo: '', // logo图片地址
					text: '', // 悬浮文本内容
					'text-color': '', // 悬浮文本颜色
					'text-stroke': '' // 悬浮文本描边
				},
				templateList: [{
					name: 'default',
					label: '默认'
				}, {
					name: 'water',
					label: '液态'
				}, {
					name: 'diamond',
					label: '菱形'
				}, {
					name: 'hexagon',
					label: '六边形'
				}, {
					name: 'star',
					label: '星星'
				}, {
					name: 'rect',
					label: '方块'
				}, {
					name: 'bar',
					label: '条形'
				}, {
					name: 'heart',
					label: '心形'
				}, {
					name: 'glitter',
					label: '闪烁'
				}, {
					name: 'stroke',
					label: '描边'
				}, {
					name: 'fusion',
					label: '融合'
				}],
				pickColorData: {
					scrollTop: 0,
					color: {
						r: 255,
						g: 255,
						b: 255,
						a: 1
					},
					title: '颜色选择',
				},
				qrcodeKey: '',
				systemPreset: [{
						width: 80,
						height: 80,
						template: 'fusion',
						level: 'M',
						// 'background-image': pic_1,
						'background-color': '#ffcc60'
					}
					// , {
					// 	width: 80,
					// 	height: 80,
					// 	template: 'fusion',
					// 	level: 'M',
					// 	'background-image': pic_2,
					// 	'background-color': '#ece8dd',
					// 	'foreground-color': '#000000',
					// 	'text-color': '#2c2b2e',
					// 	'text-stroke': '#ece8dd'
					// }
					, {
						width: 80,
						height: 80,
						template: 'diamond',
						logo: pic_3,
						'foreground-image': pic_3_1,
						'background-color': '#fff2dc',
						'inner-color': '#094304'
					}, {
						width: 80,
						height: 80,
						template: 'water',
						logo: pic_4,
						'foreground-color': '#6d327c,#485DA6,#00a1ba,#00BF98,#36C486',
						'background-color': '#f1f8ff',
						'inner-color': '#845EC2'
					}, {
						width: 80,
						height: 80,
						template: 'heart',
						logo: pic_5,
						'foreground-color': '#ff9999',
						'background-color': '#fff7f7',
						'inner-color': '#ce5050'
					}, {
						width: 80,
						height: 80,
						template: 'hexagon',
						'foreground-color': '#17252a,#2b7a78,#3aafa9',
						'background-color': '#def2f1',
						'inner-color': '#17252a'
					}, {
						width: 80,
						height: 80,
						template: 'bar',
						'foreground-color': '#3b8686,#79bd9a,#f8ca00,#008c9e',
						'background-color': '#f0f5f9',
						'inner-color': '#3B4E32'
					}, {
						width: 80,
						height: 80,
						template: 'star',
						'foreground-color': '#fe4365,#fc9d9a,#6d9d88,#490a3d',
						'background-color': '#f9f1f1',
						'inner-color': '#881600',
						'outer-color': '#343838'
					}, {
						width: 80,
						height: 80,
						template: 'rect',
						'foreground-color': '#4abdac,#fc4a1a,#f7b733',
						'background-color': '#f9f6f3',
						'inner-color': '#d66c44',
						'outer-color': '#037584'
					}, {
						width: 80,
						height: 80,
						template: 'star',
						level: 'L',
						'foreground-color': '#fc9000,#ffa935,#ffb756',
						'background-color': '#034690'
					}, {
						width: 80,
						height: 80,
						template: 'stroke',
						'foreground-color': '#150f3f,#fb3242,#018bf8',
						'background-color': '#edfaff'
					}
				],
				// 方案数据
				programmeData: {},
				fileList: [],
				backgroundImage: '',
				systemtype: 'h5',
				downloadImage: '',
				qrcodePic: '',
				qrcodeStyle: {
					width: '112px',
					height: '112px'
				},
				userType: 1,
				codeObject: {},
				isQrCode: false
			};
		},
		components: {
			// tempFootball1,
			tempFootball1,
			tempFootball2,
			tempFootball3,
			tempFootball4,
			tempFootball5,
			tempFootball6,
			tempFootball7,
			tempFootball8,
			tempFootball9,
			tempFootball10,
			tempBasketball1,
			tempBasketball2,
			tempBasketball3,
			tempBasketball4,
			tempBasketball5,
			tempBasketball6,
			tempBasketball7,
			tempBasketball8,
			tempBasketball9,
			tempBasketball10
		},
		computed: {
			...mapState({
				userInfo: state => state.login.userInfo
			}),
		},
		async onLoad(options) {
			if (options.key === 'pc' && options.token) {
				// 设置token
				this.$store.commit('login/changeToken', options.token)
				this.$store.commit('login/changeUserInfo', {
					is_sale: 1
				})
				this.systemtype = 'pc'
			}
			// 更新userinfo
			try {
				await this.$store.dispatch('login/userinfoAction');
				if (Object.keys(this.userInfo).length) {
					if (this.userInfo.is_sale == 1) {
						this.getDetails({
							content_id: options.content_id
						})
					}
				}
				uni.setNavigationBarTitle({
					title: `${this.userInfo.wechat_info.title}`
				})
			} catch (error) {}
		},
		methods: {
			// 获取方案详情
			getDetails(params) {
				uni.showLoading({
					title: "海报生成中..."
				})
				getDetailsinfo({
					params
				}).then(res => {
					if (res.code == 200) {
						getCode({
							content_id: res.data.content_id,
							wechat_id: res.data.wechat_id,
							create_uid: res.data.author.user_id
						}).then(async _res => {
							this.codeObject = _res.data
							if (res.code == 200) {
								this.type = res.data.category_ids[0]
								// this.type = 4
								this.programmeData = Object.assign(res.data, {
									match_info_obj: res.data.match_info ? JSON.parse(res.data
										.match_info) : {}
								})
								imageToBase64(res.data.author.avatar_url).then(res => {
									this.programmeData['avatar_url_base64'] = res
									this.$forceUpdate()
								})

								// if (!this.codeObject.qrcode_url && this.codeObject.url) {
								// 	imageToBase64(this.codeObject.url).then(res => {
								// 		this.qrcodePic = res
								// 	})
								// } else {
								// 	this.qrcodePic = `${window.location.origin}/${this.codeObject.qrcode_url}`
								// }
								
								this.activeConfig.com = `${this.type==3 ? 'tempFootball1' : 'tempBasketball1'}`
								
								this.handleTemplate({
									value: this.codeObject.url
								})
								// systemPreset 配置value
								this.setSystemPresetValue(this.codeObject.url)
								this.isView = true
								uni.hideLoading()

								setTimeout(() => {
									const element = this.$refs.codeID
									if (!Object.keys(element).length) {
										this.isQrCode = true
										this.qrcodePic = `${window.location.origin}/${this.codeObject.qrcode_url}`
										uni.showToast({
											icon: 'none',
											title: '你的手机系统版本过低，美化二维码暂不支持'
										});
									}
								}, 500)
							}
						})
					}
				})
			},
			setSystemPresetValue(value) {
				this.systemPreset.forEach(item => {
					item['value'] = value
				})
			},
			// 图片转base64
			// async imageToBase64(key, src) {
			// 	const response = await fetch(src);
			// 	const blob = await response.blob();
			// 	const reader = new FileReader();
			// 	reader.onloadend = () => {
			// 		this.programmeData[key] = reader.result
			// 		this.$forceUpdate()
			// 	};
			// 	reader.readAsDataURL(blob);
			// },
			// 上传海报
			posterAfterRead(type) {
				uni.chooseImage({
					sizeType: 'compressed',
					count: 1, // 2.2.0 版本起插入图片时支持多张（修改图片链接时仅限一张）
					success: async res => {
						uni.showLoading({
							title: '上传中'
						});

						for (let file of res.tempFiles) {
							// 依次上传
							const result = await addFile({
								// #ifdef H5 || APP-PLUS
								timeout: 60000, // H5(HBuilderX 2.9.9+)、APP(HBuilderX 2.9.9+)
								// #endif
								file: file,
								name: 'file',
								formData: {
									group_id: type
								}
							})
							if (result.code === 200) {
								if (type == 1) {
									this.getFileList()
								} else {
									imageToBase64(result.data.file_url).then(res => {
										this.handleTemplate({
											logo: res
										})
									})
								}
							}
						}
					},
					fail: res => {
						console.log(res)
					}
				})
			},
			// 切换模板
			getTemplate(item) {
				this.selectTemplate = item
				if (item <= 5) {
					this.qrcodeData.width = 112
					this.qrcodeData.height = 112
					this.qrcodeStyle = {
						width: '112px',
						height: '112px'
					}
				} else {
					this.qrcodeData.width = 100
					this.qrcodeData.height = 100
					this.qrcodeStyle = {
						width: '100px',
						height: '100px'
					}
				}
				this.activeConfig.com = `${this.type==3?'tempFootball':'tempBasketball'}${item}`
			},
			handlepickColor(type) {
				this.qrcodeKey = type
				if (!this.qrcodeData[this.qrcodeKey]) {
					this.isUvPickColor = true
					this.$nextTick(() => {
						this.$refs[`pickColor`].open();
					})
					return
				}
				if (!this.checkRGBA(this.qrcodeData[this.qrcodeKey])) {
					let _rgba = this.HexToRGB(this.qrcodeData[this.qrcodeKey], 1)
					let _toRGBAObject = this.toRGBAObject(_rgba)
					this.pickColorData.color = {
						r: _toRGBAObject.r,
						g: _toRGBAObject.g,
						b: _toRGBAObject.b,
						a: 1
					}
				} else {
					let _toRGBAObject = this.toRGBAObject(this.qrcodeData[this.qrcodeKey])
					this.pickColorData.color = {
						r: _toRGBAObject.r,
						g: _toRGBAObject.g,
						b: _toRGBAObject.b,
						a: _toRGBAObject.a
					}
				}

				console.log(this.pickColorData.color)
				this.isUvPickColor = true
				this.$nextTick(() => {
					this.$refs[`pickColor`].open();
				})
			},
			confirm(e) {
				console.log('confirm', e);
				const rgba = `rgba(${e.rgba.r},${e.rgba.g},${e.rgba.b},${e.rgba.a})`
				const rgb = `rgb(${e.rgba.r},${e.rgba.g},${e.rgba.b})`
				if (this.qrcodeKey == 'foreground-color') {
					// this.qrcodeData[this.qrcodeKey] = uni.$u.rgbToHex(rgb)
					let v = {}
					v[this.qrcodeKey] = uni.$u.rgbToHex(rgb)
					this.handleTemplate(v)
				} else {
					// this.qrcodeData[this.qrcodeKey] = rgba
					let v = {}
					v[this.qrcodeKey] = uni.$u.rgbToHex(rgba)
					this.handleTemplate(v)
				}
			},
			cancel() {
				this.isUvPickColor = false
			},
			close() {
				this.isUvPickColor = false
			},
			captureScreenshot() {
				const element = document.getElementById('screenshotTarget');
				html2canvas(element).then((canvas) => {
					const imgData = canvas.toDataURL('image/png');
					this.saveImage(imgData);
				});
			},
			saveImage(dataUrl) {
				if (this.systemtype == 'pc') {
					const link = document.createElement('a');
					link.href = dataUrl;
					link.download = 'screenshot.png';
					document.body.appendChild(link);
					link.click();
					document.body.removeChild(link);
				} else {
					console.log(dataUrl)
					this.downloadImage = dataUrl
				}
			},

			toRGBAObject(rgbaStr) {
				let [r, g, b, a] = rgbaStr.match(/\d+(\.\d+)?/g).map(Number);
				return {
					r,
					g,
					b,
					a
				};
			},
			RGBToHex(rgba) {
				let str = rgba.slice(5, rgba.length - 1),
					arry = str.split(','),
					opa = Number(arry[3].trim()),
					strHex = "#",
					r = Number(arry[0].trim()),
					g = Number(arry[1].trim()),
					b = Number(arry[2].trim());

				strHex += ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);

				return {
					color: strHex,
					opacity: opa
				};
			},
			HexToRGB(color, opacity) {
				let newColor = 'rgba(';

				//判断是三位还是六位
				if (color.length === 4) {
					let arry = [];

					for (let i = 1; i < color.length; i++) {
						arry.push(parseInt("0x" + color[i] + color[i]));
					}

					arry.forEach(function(item) {
						newColor += item + ', ';
					});
					newColor += opacity / 100 + ')';

					return newColor;
				} else {
					let arry = [];

					for (let i = 1; i < color.length; i += 2) {
						arry.push(parseInt("0x" + color.slice(i, i + 2)));
					}

					arry.forEach(function(item) {
						newColor += item + ', ';
					});
					newColor += opacity + ')';

					return newColor;
				}
			},
			checkRGBA(rgba) {
				let str = rgba.slice(5, rgba.length - 1),
					arry = str.split(','),
					status = true,
					reg = /^rgba\(\d{1,3}(\,\s{0,1}\d{1,3}){2}\,\s{0,1}(0|(0(\.\d{1,2}))|1)\)$/;

				arry.forEach(function(item, index) {
					if (index == arry.length - 1) {
						if (Number(item.trim()) < 0 || Number(item.trim()) > 1) {
							status = false;
						}
					} else {
						if (Number(item.trim()) < 0 || Number(item.trim()) > 255) {
							status = false;
						}
					}
				});

				if (reg.test(rgba) && status) {
					return true;
				} else {
					return false;
				}
			},
			handleSystemPreset(e) {
				// let copyQrcodeData = JSON.parse(JSON.stringify(this.qrcodeData))
				this.qrcodeData = e
				// for (let key of Object.keys(copyQrcodeData)) {
				// 	this.qrcodeData[key] = e[key] ? e[key] : copyQrcodeData[key]
				// }
				// this.visible = false
				// this.activeConfig.com = tempFootball6
				// setTimeout(() => {
				// 	this.visible = true
				// }, 2000)
			},
			handleTemplate(e) {
				let copyQrcodeData = JSON.parse(JSON.stringify(this.qrcodeData))
				if (e.template == 'fusion' && copyQrcodeData['foreground-color'].length != 7) {
					copyQrcodeData['foreground-color'] = '#000000'
				}
				this.qrcodeData = Object.assign(copyQrcodeData, e)
				this.$forceUpdate()
			},
			async openPoster() {
				this.$refs.posterPopup.open('bottom')
				this.getFileList()
			},
			async getFileList() {
				const result = await fileList({
					page: 1,
					limit: 999,
					sort_value: 'desc',
					group_id: '1'
				})
				if (result.code === 200) {
					this.fileList = result.data.list
				}
			},
			// 删除图片
			async deletePic(e) {
				const result = await deleFile({
					ids: [e.file_id]
				})
				if (result.code === 200) {
					// uni.showToast({
					// 	title: '操作成功!',
					// 	icon: 'none'
					// })
					this.getFileList()
				}
			},
			// 选中自定义海报
			async selectCustomPoster(e) {
				let url = e + '?t=' + new Date().getTime()
				imageToBase64(url).then(res => {
					this.backgroundImage = res
					this.$forceUpdate()
					this.$refs.posterPopup.close()
				})
			},
			setUserType(type) {
				this.userType = type
				if (this.isQrCode) {
					// 低版本设备
					// 新用户
					if (type == 1) {
						this.qrcodePic = `${window.location.origin}/${this.codeObject.qrcode_url}`
					}
					// 老用户
					if (type == 2) {
						this.qrcodePic = `${window.location.origin}/${this.codeObject.content_url_code}`
					}
				} else {
					// 新用户
					if (type == 1) {
						this.handleTemplate({
							value: this.codeObject.url
						})
						// systemPreset 配置value
						this.setSystemPresetValue(this.codeObject.url)
					}
					// 老用户
					if (type == 2) {
						this.handleTemplate({
							value: this.codeObject.content_url
						})
						// systemPreset 配置value
						this.setSystemPresetValue(this.codeObject.content_url)
					}
				}
				
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import url('./index.scss');
	
	page {
		background-color: #ffffff !important;
	}

	.poster-box {
		&-item {
			position: relative;
			cursor: pointer;
			margin-right: 5px;
			margin-bottom: 5px;
		}

		&-item.active {
			border: 2px dashed #578bd6;
			padding: 2px;
		}
	}

	.popup {
		padding: 0 16px;

		.close-popup {
			height: 56px;
			display: flex;
			justify-content: center;
			align-items: center;
			position: relative;
			font-size: 14px;
			color: #000000;
			line-height: 24px;
		}

		.bj-color {
			width: 100%;
			height: 48px;
			background: linear-gradient(270deg, #FE7B45 0%, #FB541D 100%);
			font-size: 14px;
			color: #FFF0ED;
			line-height: 48px;
			text-align: center;
			border-radius: 800px;
			margin: 10px 0 6px;
		}
	}
	
	.custom-select-btn {
		.item {
			width: 65px;
			height: 30px;
			line-height: 30px;
			text-align: center;
			background-color: #FFFFFF;
			color: #666666;
			border: 1px solid #E5E5E5;
			border-radius: 4px;
			margin-right: 10px;
			box-sizing: content-box;
			cursor: pointer;
		}
	
		.item.active {
			background-color: #52B36D;
			color: #FFFFFF;
			border: 1px solid #52B36D;
		}
	}
</style>